package com.graduate.daydayup.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.AlarmClock
import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.graduate.daydayup.App
import com.graduate.daydayup.R
import com.graduate.daydayup.base.BaseActivity
import com.graduate.daydayup.room.MyRoomDataBase
import com.graduate.daydayup.room.Schedule
import com.graduate.daydayup.view.MyPickerView
import kotlinx.android.synthetic.main.activity_editschedule.*
import kotlinx.android.synthetic.main.activity_lessonadd.*
import kotlinx.android.synthetic.main.activity_lessonadd.et_lesson_location
import kotlinx.android.synthetic.main.activity_lessonadd.et_lesson_name
import kotlinx.android.synthetic.main.activity_lessonadd.et_lesson_teacher
import kotlinx.android.synthetic.main.activity_lessonadd.ll_alarm
import kotlinx.android.synthetic.main.activity_lessonadd.ll_weekdays
import kotlinx.android.synthetic.main.activity_lessonadd.ll_weeks
import kotlinx.android.synthetic.main.activity_lessonadd.tv_alarmtime
import kotlinx.android.synthetic.main.activity_lessonadd.tv_weekdays
import kotlinx.android.synthetic.main.activity_lessonadd.tv_weeks
import kotlin.random.Random

class EditScheduleActivity: BaseActivity() {
    val default="8:20,\n9:15,\n10:15,\n11:10,\n13:00,\n13:55,\n14:50,\n16:45,\n18:30,\n19:25,\n20:20"

    var start=0
    var step=0
    var day=0
     var weeklist=""
    override fun setTitle()="课程详情"

    override fun getLayout()= R.layout.activity_editschedule

    override fun setTextRight()="修改"
    lateinit var roomSchedule: Schedule
    override fun setImgRightListener() {
        if (TextUtils.isEmpty(et_lesson_name.text.toString())){
            ToastUtils.showShort("课程名为空")
            return
        }
        if (TextUtils.isEmpty(et_lesson_teacher.text.toString())){
            ToastUtils.showShort("老师为空")
            return
        }
        if (TextUtils.isEmpty(tv_weeks.text.toString())){
            ToastUtils.showShort("周数为空")
            return
        }
        if (TextUtils.isEmpty(tv_weekdays.text.toString())){
            ToastUtils.showShort("第几节课为空")
            return
        }
        if (TextUtils.isEmpty(et_lesson_location.text.toString())){
            ToastUtils.showShort("上课地点为空")
            return
        }

            val intExtra = intent.getIntExtra("id", -1)
            if (intExtra!=-1){
                val random = Random(10)
                roomSchedule=Schedule(intent.getIntExtra("id",0), et_lesson_name.text.toString(), et_lesson_location.text.toString(),
                    et_lesson_teacher.text.toString(),weeklist, start, step-start+1, day,
                    random.nextInt())
                MyRoomDataBase.getInstance(App.instance!!).scheduleDao().updateSchedule(roomSchedule)
                if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString("lessontime").isEmpty()){
                    val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
                    val split = replace.split(",")
                    val split1 = split[start-1].split(":")
                    Log.d("设置闹钟", split1[0]+ split1[1])
                    setSystemAlarmClock(this,"在${roomSchedule.room}上${roomSchedule.teacher}的${roomSchedule.name}",day,split1[0].toInt(),split1[1].toInt())
                }else{
                    val replace = default.replace("\n", "")
                    val split = replace.split(",")
                    val split1 = split[start-1].split(":")
                    Log.d("设置闹钟", split1[0]+ split1[1])
                    setSystemAlarmClock(this,"在${roomSchedule.room}上${roomSchedule.teacher}的${roomSchedule.name}",day,split1[0].toInt(),split1[1].toInt())
                }
                ToastUtils.showShort("修改成功")
                finish()
            }
    }

    override fun isAddToolbar()=true

    override fun initViewIds() {

    }

    override fun initView() {
        val intExtraId = intent.getIntExtra("id", 0)
        start = intent.getIntExtra("start", 0)
        day = intent.getIntExtra("day", 0)-1
        step = intent.getIntExtra("step", 0)
        val allById = MyRoomDataBase.getInstance(this).scheduleDao().getAllById(intExtraId)
        weeklist=allById.weeklist
            var day_string=""
            when(day){
                1->day_string="一"
                2->day_string="二"
                3->day_string="三"
                4->day_string="四"
                5->day_string="五"
                6->day_string="六"
                7->day_string="日"
            }
            tv_weekdays.setText("周${day_string}第${start}节第${step+start-1}节")
            if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString(
                    "lessontime"
                ).isEmpty()){
                val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }else{
                val replace = default.replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start - 1].split(":")
                Log.d("设置闹钟", split1[0] + split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }

        val pickview= MyPickerView(this)
        val pickview_weeks= MyPickerView(this)
        var listItem1=ArrayList<String>()
        var listItem2=ArrayList<String>()
        var listItem3=ArrayList<String>()
        var listItem4=ArrayList<String>()
        var listItem5=ArrayList<String>()
        listItem1.add("周一")
        listItem1.add("周二")
        listItem1.add("周三")
        listItem1.add("周四")
        listItem1.add("周五")
        listItem1.add("周六")
        listItem1.add("周日")
        val index = SPUtils.getInstance().getInt("lessoncounts", 8)
        for (i in 1..index){
            listItem2.add("第${i}节")
        }
        for (i in 1..index){
            listItem3.add("第${i}节")
        }
        pickview.setPicker(listItem1, listItem2, listItem3, false)
        pickview.setSelectOptions(day-2,start-1,step+start)
        ll_weekdays.setOnClickListener {
            pickview.show()
        }
        pickview.setOnoptionsSelectListener { options1, option2, options3 ->
            if (options3<option2){
                ToastUtils.showShort("不符合规则,请重新选择")
            }else{
                start=option2+1
                step=options3+1
                day=options1+1
                Log.d("zlytest","${options1},${option2},${options3}")
                tv_weekdays.text = listItem1.get(options1)+listItem2.get(option2)+listItem2.get(options3)
            }
            if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString("lessontime").isEmpty()){
                val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start-1].split(":")
                Log.d("设置闹钟", split1[0]+ split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }else{
                val replace = default.replace("\n", "")
                val split = replace.split(",")
                val split1 = split[start-1].split(":")
                Log.d("设置闹钟", split1[0]+ split1[1])
                tv_alarmtime.setText("${split1[0]}:${split1[1]}")
//                setSystemAlarmClock(this,"在${et_lesson_location.text.toString()}上${et_lesson_teacher.text.toString()}的${et_lesson_name.text.toString()}",split1[0].toInt(),split1[1].toInt())
            }
        }
        for (i in 1..25){
            listItem4.add("第"+i.toString()+"周")
            listItem5.add("第"+i.toString()+"周")
        }
        val split2 = allById.weeklist.split(",")
        val m1=split2[0].toInt()-1
        val m2=split2[1].toInt()-1
        tv_weeks.text="第${split2[0].toInt()}周到第${split2[1].toInt()}周"
        pickview_weeks.setSelectOptions(m1,m2)
        pickview_weeks.setPicker(listItem4,listItem5,false)
        ll_weeks.setOnClickListener {
            pickview_weeks.show()
        }
        pickview_weeks.setOnoptionsSelectListener { options1, option2, options3 ->
            if (options1>option2){
                ToastUtils.showShort("不符合规则,请重新选择")
            }else{
                tv_weeks.text = "${listItem4.get(options1)}到${listItem5.get(option2)}"
                Log.d("zlytest","${options1+1},${option2+1}")
                weeklist="${options1+1},${option2+1}"
            }
        }
        ll_alarm.setOnClickListener {
            ActivityUtils.startActivity(Intent(AlarmClock.ACTION_SHOW_ALARMS))
        }
        tv_delete.setOnClickListener {
            val intExtra = intent.getIntExtra("id", -1)
            if (intExtra!=-1){
                val allById = MyRoomDataBase.getInstance(App.instance!!).scheduleDao()
                    .getAllById(intent.getIntExtra("id", -1))
                MyRoomDataBase.getInstance(App.instance!!).scheduleDao().deleteBySchedule(allById)
                ToastUtils.showShort("删除成功")
                finish()
            }

        }

    }


    override fun initData(savedInstanceState: Bundle?) {
        val intExtra = intent.getIntExtra("id", -1)
        if (intExtra!=-1){
            val allById = MyRoomDataBase.getInstance(App.instance!!).scheduleDao()
                .getAllById(intExtra)
            et_lesson_name.setText(allById.name)
            et_lesson_teacher.setText(allById.teacher)
            et_lesson_location.setText(allById.room)
        }

    }

    fun setSystemAlarmClock(context: Context, message: String?, days:Int, hour: Int, minute: Int): Boolean {
        if (Build.VERSION.SDK_INT < 9) {
            return false
        }
        val intent = Intent(AlarmClock.ACTION_SET_ALARM)
        intent.putExtra(AlarmClock.EXTRA_MESSAGE, message)
        intent.putExtra(AlarmClock.EXTRA_HOUR, hour)
        intent.putExtra(AlarmClock.EXTRA_MINUTES, minute)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 11) {
            intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
        }
        if (Build.VERSION.SDK_INT >= 19) {
            intent.putExtra(AlarmClock.EXTRA_VIBRATE, true)
        }
        return try {
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

}